<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="收费项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入收费项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司类型" prop="companyType">
        <el-select v-model="queryParams.companyType" placeholder="请选择公司类型" clearable size="small">
          <el-option
            v-for="dict in companyTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="hide">
        <el-select v-model="queryParams.hide" placeholder="请选择是否显示" clearable size="small">
          <el-option
            v-for="dict in hideOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:appcostproject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:appcostproject:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:appcostproject:remove']"
        >删除</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:appcostproject:export']"
        >导出</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="appcostprojectList" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="颜色" align="left" prop="color" width="60">
        <template slot-scope="scope">
          <el-image style="width: 38px; height: 38px" :src="'../prod-api/app/files/' + scope.row.color" :fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="收费项目名称" align="left" prop="name" />
      <el-table-column label="公司类型" align="left" prop="companyType"  :formatter="companyTypeFormat" />

      <el-table-column label="排序" align="left" prop="sort" width="120"/>
      <el-table-column label="是否显示" align="left" prop="hide" :formatter="hideFormat" width="120"/>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:appcostproject:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:appcostproject:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

 <!--   <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->

    <!-- 添加或修改收费项目对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入收费项目名称" />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <!--<el-color-picker v-model="form.color"></el-color-picker>-->
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, '1')"
                :http-request="uploadCompnayPic">
                <img v-if="form.color" :src="'../prod-api/app/files/' + form.color" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort"  label="描述文字" placeholder="请输入排序(值越大越靠前)"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="公司类型">
              <el-radio-group v-model="form.companyType">
                <el-radio
                  v-for="dict in companyTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示">
              <el-radio-group v-model="form.hide">
                <el-radio
                  v-for="dict in hideOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>






        <el-form-item label="收费标准">
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAddCategory">增加一条数据</el-button>
          <el-table
            style="width: 100%"
            :data="form.children">
            <el-table-column
              type="index"
              width="50">
            </el-table-column>

            <el-table-column label="最小单位" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.minNum" size="small" ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="最大单位" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.maxNum" size="small" ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="单价(元)" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.money" size="small"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="单位(例:吨、个、瓶)" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unit" placeholder="请输入单位"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="120px"
                             label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelCategory(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listAppcostproject, getAppcostproject, delAppcostproject, addAppcostproject, updateAppcostproject } from "@/api/app/appcostproject";
import { listAppcostcategoryrates} from "@/api/app/appcostcategoryrates";
import {uploadCompnayPic} from "@/api/app/appcostcompany";

export default {
  name: "Appcostproject",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 收费项目表格数据
      appcostprojectList: [],
      // 收费标准表格数据
      appcostcategoryratesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示字典
      hideOptions: [],
      companyTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 500,
        name: undefined,
        companyType: undefined,
        hide: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "收费项目名称不能为空", trigger: "blur" }
        ],
        companyType: [
          { required: true, message: "公司类型", trigger: "blur" }
        ],
        color: [
          { required: true, message: "颜色不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序（值越大越靠前）不能为空", trigger: "blur" }
        ],
        hide: [
          { required: true, message: "是否显示不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_show_hide").then(response => {
      this.hideOptions = response.data;
    });
    this.getDicts("app_company_type").then(response => {
      this.companyTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询收费项目列表 */
    getList() {
      this.loading = true;
      listAppcostproject(this.queryParams).then(response => {
        this.appcostprojectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCategoryList(cid) {
      this.loading = true;
      var that = this;
      var param = {pageNum: 1,pageSize: 500 , cid: cid};
      listAppcostcategoryrates(param).then(response => {
        this.form.children = response.rows;
        this.loading = false;
      });
    },
    // 是否显示字典翻译
    hideFormat(row, column) {
      return this.selectDictLabel(this.hideOptions, row.hide);
    },
    companyTypeFormat(row, column) {
      return this.selectDictLabel(this.companyTypeOptions, row.companyType);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        companyType: "1",
        color: "",
        sort: 30,
        hide: "0",
        createTime: undefined,
        children: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收费项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAppcostproject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收费项目";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAppcostproject(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAppcostproject(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除收费项目编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAppcostproject(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/appcostproject/export', {
        ...this.queryParams
      }, `app_appcostproject.xlsx`)
    },
    handleAddCategory(){
      let project= {};
      this.form.children.push(project);
      console.log(this.form.children);
    },
    handleDelCategory(index , row){
      console.log(index);
      this.form.children.splice(index, 1);

      // for (let i = 0; i < list.length; i++) {
      //   if (list[i].id == row.index) {
      //     list.splice(i, 1);
      //   }
      //
      // }
    },
    uploadCompnayPic(param) {
      var fileObj = param.file;
      // FormData 对象
      var formData = new FormData();
      // 文件对象
      formData.append("picfile", fileObj);
      uploadCompnayPic(formData)
        .then(response => {
          if (response.code === 200) {
            //this.msgSuccess("附件上传成功");
            //this.form.testifyFile = response.url;
            //上传成功 调用onSuccess方法，否则没有完成图标
            //处理自己的逻辑
            param.onSuccess(response);
            fileObj.url = response.url;
          } else {
            this.msgError(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handlePreview(file) {
      this.form.uploadCompnayPic = file.url;
      console.log("---------------handlePreview--------------");
    },
    handleRemove(file, fileList) {
      console.log("---------------handleRemove--------------");
      // var that = this;
      // that.form.testifyFile = JSON.stringify(fileList);
      // console.log(that.form.testifyFile);
    },
    handleSuccess(response, file, fileList, type) {
      console.log(response);

      if(response.code && response.code == 200){
        console.log(response.data);
        this.form.color = response.data;

        console.log(this.form.color);
      }
    },
    handlePictureCardPreview(file) {
      this.form.licensePic = file.url;
    },
  }
};
</script>
<style >
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .avatar {
    width: 140px;
    height: 140px;
    display: block;
  }
</style>



